package com.wswy.wzcx.ui.main.community.detail

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.util.Log
import com.che.libcommon.api.ApiOptionalResultObserver
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.page.PageList
import com.che.libcommon.api.page.Pagination
import com.che.libcommon.utils.ToastUtils
import com.che.libcommon.utils.optional.Optional
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.Converter
import com.wswy.wzcx.model.topic.CommentModel
import com.wswy.wzcx.model.topic.TopicModel
import com.wswy.wzcx.module.base.ApiCallback
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.UserViewModel
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.ui.main.community.CommentVO
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.Single
import java.util.*

class CommentViewModel : UserViewModel() {

    private val listLiveData = MutableLiveData < Resource<List<Any>> >()


    private val topicLiveData = MutableLiveData<TopicModel?>()

    private var tmpCms:MutableList<Any>?=null

    private var sendingCms : Boolean = false

    override fun onCreate() {
        super.onCreate()
        registerObservers()
    }


    var pagination: Pagination<CommentModel>? = null
        private set

    fun load(topicModel: TopicModel){


        topicLiveData.value = topicModel

        loadComments(topicModel.id)

    }

    private fun loadComments(topicId:Long){
        pagination?.release()

        val api: (Int) -> Single<Optional<PageList<CommentModel>>> = {

            Api.get().getCommentList(it, topicId).compose(RxUtils.switch2io())
        }

        tmpCms = null

        pagination = if (pagination == null) Pagination<CommentModel>(api) else pagination?.setPaginationWrapper(api)

        pagination?.apply {


            setCallback(object : ApiOptionalResultObserver<List<CommentModel>>() {


                override fun onApiResult(t: List<CommentModel>?) {

                    val ret = arrayListOf<CommentVO>()

                    t?.forEach {
                        ret.add(Converter.convert2CommentVO(it))
                    }

                    if (isFirst && t != null){

                        val list = arrayListOf<Any>()

                        list.addAll(ret)

                        topicLiveData.value?.run {
                            list.add(0,Converter.convert2TopicVO(this)) //贴子
                            list.add(1,this.commentNumber.toString()) //评论数

                            listLiveData.postValue(Resource.success(list,true))
                        }?:kotlin.run {
                            tmpCms = list
                        }

                    }else{
                        tmpCms = null
                        listLiveData.postValue(Resource.success(ret))
                    }

                }

                override fun onApiError(result: BaseResult<*>?) {

                    if (isFirst){
                        listLiveData.postValue(Resource.error(result,isFirst))
                    }
                }
            })


        }

        pagination?.preLoad()
    }



    fun load(topicId:Long){
        addRun(Api.get().topicView(topicId).onResult({

            it?.topic?.run {


                topicLiveData.value = this

                val topic = this

                tmpCms?.run {

                    add(0,Converter.convert2TopicVO(topic)) //贴子
                    add(1,topic.commentNumber.toString()) //评论数

                    listLiveData.postValue(Resource.success(this,true))
                }

            }


        },{

            listLiveData.postValue(Resource.error(it,true))

            ApiCallback.toastErrorMsg(it)
        }))

        loadComments(topicId)
    }


    fun addComment(content:String?){
        if (sendingCms){


            return
        }

        sendingCms = true
        val id = topicLiveData.value?.id?:return
        addRun(Api.get().addComment(id,content).onResult({
            sendingCms = false
            it?.run {

                listLiveData.postValue(Resource.success(Collections.singletonList(Converter.convert2CommentVO(this)),false,100))
            }

        },{
            sendingCms = false
            ApiCallback.toastErrorMsg(it)
        }))

    }

    fun getCommentsLiveData():LiveData<Resource<List<Any>> > = listLiveData


    fun isSending() = sendingCms


    fun getTopic() = topicLiveData.value



    override fun onCleared() {
        super.onCleared()
        pagination?.release()
    }
}